//
//  MusicManager.m
//  PhageWar
//
//  Created by Tran Dang Khoa on 4/16/09.
//  Copyright 2009 HCMUT. All rights reserved.
//

#import "MusicManager.h"

@implementation MusicManager

static GBMusicTrack *track;
static NSMutableDictionary *trackFiles;
static BOOL enabled_=TRUE;
static BOOL musicVolume_=1.0f;

+(void) addMusicTrack:(NSString*)filename name:(NSString*)name {
	if (trackFiles == nil) {
		trackFiles = [[NSMutableDictionary alloc] init];
	}
	[trackFiles setObject:filename forKey:name];
}
+ (BOOL)hasMusicTrack:(NSString*)name {
	id obj = [trackFiles objectForKey:name];
	if(obj==nil) return FALSE;
	else
		return TRUE;
}

+ (void)playMusicTrack:(NSString*)name withRepeat:(BOOL)b {
#ifndef DEBUG_NO_SOUND
	[self stopCurrentTrack];
	
	if (!enabled_) return;
	if (trackFiles == nil) return;
	
	track = [[GBMusicTrack alloc] initWithPath:[[NSBundle mainBundle] pathForResource:[trackFiles objectForKey:name] ofType:@"mp3"]];
	[track setRepeat:b];
	[track setVolume:musicVolume_];
	[track play];
#endif
}
+(void) playMusicTrack:(NSString*)name {
	[self playMusicTrack:name withRepeat:YES];
}

+(void) playRandomTrack {
#ifndef DEBUG_NO_SOUND
	[self stopCurrentTrack];
	
	if (!enabled_) return;
	if (trackFiles == nil) return;
	NSArray *tracks = [[trackFiles objectEnumerator] allObjects];
	int nTracks = [tracks count];
	int iTrack = (random()*1000) % nTracks;
	if(iTrack<0 || (iTrack>nTracks-1)) iTrack = 0;
	track = [[GBMusicTrack alloc] initWithPath:[[NSBundle mainBundle] pathForResource:[tracks objectAtIndex:iTrack] ofType:@"mp3"]];
	[track setRepeat:YES];
	[track setVolume:musicVolume_];
	[track play];
#endif
}

+ (void)stopCurrentTrack {
	if (track != nil) {
		[track pause];
		[track close];
		[track release];
		track = nil;
	}
}

+(void) removeAll {
	if (track != nil) {
		[track pause];
		[track close];
		[track release];
		track = nil;
	}
	if (trackFiles != nil) {
		[trackFiles removeAllObjects];
		[trackFiles release];
		trackFiles = nil;
	}
}

+(void) setVolume:(float)newValue {
	//[track setVolume:newValue];
	musicVolume_ = newValue;
}

+ (float)volume {
	return musicVolume_;
}

+ (void)setEnabled:(BOOL)b {
	enabled_ = b;
//#ifndef DEBUG_NO_SOUND
	if(!enabled_) {
		[self stopCurrentTrack];
	}
//#endif
}
+ (BOOL)enabled {
	return enabled_;
}
@end
